package org.tinygroup.bizframe.common;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.tinygroup.beancontainer.BeanContainerFactory;
import org.tinygroup.bizframe.common.impl.DefaultAuditLogger;
import org.tinygroup.cache.Cache;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

/**
 * Created by Mr.wang on 2016/6/12.
 */
public class BaseController {
	
	@InitBinder  
	public void initBinder(WebDataBinder binder) {  
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
		dateFormat.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	    
	    getAuditLogger();
	}
    private Cache cache;
    
    protected AuditLogger auditLogger;
    
    /**
     * 拼装前台Ajax请求结果
     *
     * @param result
     * @param msg
     * @return
     */
    protected Map<String, Object> resultMap(boolean result, final String msg) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (result) {
            map.put("status", "y");
        } else {
            map.put("status", "n");
        }
        map.put("info", msg);
        return map;
    }
    protected Map<String, Object> resultMap(boolean result, Map<String, Object> map) {
    	if(map == null){
    		map = new HashMap<String, Object>();
    	}
    	if (result) {
    		map.put("status", "y");
    	} else {
    		map.put("status", "n");
    	}
//    	map.put("info", msg);
    	return map;
    }

    /**
     * 拼装前台Ajax请求结果
     * 返回状态为int类型
     * @param result
     * @param msg
     * @return
     */
    protected Map<?, ?> resultMap(Integer result, final String msg) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", result);
        map.put("info", msg);
        return map;
    }

    protected Cache getCache(){
        if(cache==null){
            cache = BeanContainerFactory.getBeanContainer(BaseController.class.getClassLoader()).getBean("cacheBean");
        }
        return cache;
    }
    
    protected AuditLogger getAuditLogger(){
        if(auditLogger==null){
        	try{
	        	auditLogger = BeanContainerFactory.getBeanContainer(BaseController.class.getClassLoader()).getBean(AuditLogger.BEAN_NAME);
        	}
        	catch(NoSuchBeanDefinitionException e){
        		auditLogger=new DefaultAuditLogger();
        	}
        }
        return auditLogger;
    }
    
    /**
     * 以流的形式下载文件
     * @param is
     * @param response
     * @param fileName
     */
    protected void downloadFile(InputStream is,HttpServletResponse response,String fileName) {
        try {
            // 以流的形式下载文件。
            BufferedInputStream fis = new BufferedInputStream(is);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"),"ISO-8859-1"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            
         } 
         catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    } 
}
